package classes.Commands
{
	import UIUtils.uif_tb;
	import UIUtils.uif_util;
	
	import classes.c_util;
	
	import components.editor.c_baseEditor;
	import components.editor.c_baseElement;
	import components.editor.c_bitmapMaskElement;
	import components.editor.c_holeyElement;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BitmapDataChannel;
	import flash.display.BlendMode;
	import flash.display.DisplayObject;
	import flash.filters.ColorMatrixFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class c_insertMaskCommand extends c_commandFromEditor {
		private var _source		: DisplayObject;
		private var _index		: int;
		private var _params		: Object;
		public function c_insertMaskCommand(a_editor: c_baseEditor, a_source: DisplayObject, a_params: Object) {
			super(a_editor);
			_source = a_source;
			_params	= a_params;
		}
		
		override public function Execute():void {
			super.Execute();
			if (!element) {
				_element 	= createMaskElement();
				_index 		= element.index;
			} else element.setParent(editor.imageLayer, _index);
			editor.dragRect.link = element;
		}
		
		protected function createMaskElement(): c_baseElement {
			
			var rect: Rectangle = uif_util.EnterHere(editor.imageLayer.getInner(), new Point(_source.width, _source.height));
			var bmd: BitmapData = new BitmapData(rect.width, rect.height, false, 0);
			var gray: ColorMatrixFilter = new ColorMatrixFilter(c_util.SaturationArray(0));
			bmd.draw(_source);
			bmd.applyFilter(bmd, bmd.rect, uif_util.NULLPOINT, gray);
			
			var bmd_mask: BitmapData = new BitmapData(rect.width, rect.height, true, 0);
			bmd_mask.copyChannel(bmd, bmd.rect, uif_util.NULLPOINT, BitmapDataChannel.GREEN, BitmapDataChannel.ALPHA);
			var spots: Array = uif_tb.searchSpots(bmd_mask);
			var _mask: c_bitmapMaskElement = new c_bitmapMaskElement(editor.imageLayer, rect, new Bitmap(bmd_mask), spots, _params);
			
			bmd_mask.dispose();
			bmd.dispose();
			return _mask;
		}
		
		override public function unExecute():void {
			element.remove();
			super.unExecute();
		}
		
		override public function dispose():void {
			element.dispose();
			super.dispose();
		}
	}
}